/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.com.wholeconsulting.pacc.gui.utils.frame;

import ar.com.wholeconsulting.pacc.persistance.JPASession;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityTransaction;
import javax.swing.JFrame;

/**
 *
 * @author Duco Pablo
 */
public abstract class SaveOnCloseFrame extends JFrame {

    private EntityTransaction transaction;
    protected boolean isNew = false;
    protected Object currentObj;
    protected boolean ok;

    public SaveOnCloseFrame() {
        transaction = JPASession.getInstance().getManager().getTransaction();
        transaction.begin();
    }

    @Override
    public void setVisible(boolean b) {
        if (!b) {
            if (isOk()) {
                saveChanges();
            } else {
                rollbackChanges();
            }
        }
        super.setVisible(b);
    }

    private void rollbackChanges() {
        try {
            transaction.rollback();
        } catch (Exception ex) {
            Logger.getLogger(SaveOnCloseFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void saveChanges() {
        try {

            saveNewObjects();
            //JPASession.getInstance().getManager().persist(currentObj);
            transaction.commit();
        } catch (Exception ex) {
            Logger.getLogger(SaveOnCloseDialog.class.getName()).log(Level.SEVERE, null, ex);
            transaction.rollback();
        }
    }

    public boolean isOk() {
        return ok;
    }

    protected abstract void saveNewObjects();
}
